package category

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"gorm.io/gorm"
	"insighttracking/apps/admin/auth"
	"insighttracking/query/service"
	"net/http"

	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type ModifyCategoryStatusByIdApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewModifyCategoryStatusByIdApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *ModifyCategoryStatusByIdApiLogic {
	hostname, _ := os.Hostname()
	return &ModifyCategoryStatusByIdApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *ModifyCategoryStatusByIdApiLogic) ModifyCategoryStatusByIdApi(req *types.IdReq) (resp string, err error) {
	// todo: add your logic here and delete this line
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return "", err
	}
	categoryEntity, err := service.CategoryService.GetByIdApi(l.ctx, accountInfo.EnterpriseId, req.Id)
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return "", err
	}

	status := k.If(categoryEntity.Status == 2, 1, 2)
	fmt.Println(status, "当前状态")
	// 判断分类下是否有商品
	if status == 2 {
		_, err = service.CategoryService.GetByParentIdApi(l.ctx, req.Id)
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			return "", errors.New("分类下子分类不能禁用")
		}
		// 有商品的也不能禁用
		_, err = service.SpuService.GetCategorySpuByCategoryIdApi(l.ctx, req.Id)
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			return "", errors.New("分类下有商品不能禁用")
		}
	}
	if err = service.CategoryService.ModifyStatusByIdApi(l.ctx, req.Id, int64(status)); err != nil {
		return "", err
	}
	return "修改成功", nil
}
